package com.cloudloan.controller;

import com.cloudloan.common.DeployCommon;
import com.cloudloan.common.R;
import com.cloudloan.entity.Book;
import com.cloudloan.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${file.path}")
    private String filePath;
    @Autowired
    private BookMapper bookMapper;
    /**
     * 返回配置信息
     * @return
     */
    @RequestMapping("/deploy")
    public R deploycommon(){
        Map<String, Object> deploy = DeployCommon.deploy();
        return R.success(deploy);
    }
    /**
     * 上传图片
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file){ //文件上传固定格式
        Map<String ,Object> map=new HashMap<>();
        // 设置保存路径
        String uploadDir = filePath;
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 为了防止文件名冲突，使用UUID生成一个唯一的文件名
        String newFilename = UUID.randomUUID().toString() + "_" + originalFilename;
        // 创建保存文件的路径
        File destFile = new File(uploadDir + newFilename);
        // 检查目标目录是否存在，如果不存在则创建
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        try {
            // 将上传的文件保存到目标路径
            file.transferTo(destFile);
            Book book = Book.builder().image(newFilename).build();
            bookMapper.insert(book);
            map.put("id", book.getId());
            map.put("imageName", book.getImage());
            return R.success(map,"上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败：" + e.getMessage());
        }
    }
}
